package com.bootdo.system.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.SysDictDO;
import com.bootdo.common.service.SysDictService;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.system.domain.Course;
import com.bootdo.system.domain.CourseTime;
import com.bootdo.system.domain.Customer;
import com.bootdo.system.service.CourseService;
import com.bootdo.system.service.CourseTimeService;
import com.bootdo.system.service.CustomerService;
import com.bootdo.system.util.LocationUtil;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RequestMapping("/sys/course")
@Controller
@Api(value = "/sys/course", description = "课程操作接口")
public class CourseController extends BaseController {
	@Autowired
	CourseService courseService;

	@Autowired
	CustomerService customerService;
	
	@Autowired
	SysDictService sysDictService;
	
	@Autowired
	CourseTimeService courseTimeService;

	
	@ApiOperation(value="课程查询", notes="根据条件查询课程", response=String.class)
	@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "课程id", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "bdId", value = "BD的id", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "courseOwner", value = "课程所属商户Id", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "placeFirst", value = "一级地址", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "placeSecond", value = "二级地址", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "ageRange", value = "宝宝年龄段", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "coursePoints", value = "课程点数", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "courseType", value = "课程类型", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "courseSpec", value = "课程特性", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "courseStatus", value = "课程状态", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true,paramType="query", dataType = "Integer"),
        @ApiImplicitParam(name = "pageNum", value = "当前页数", required = true,paramType="query", dataType = "Integer")
	})
	@GetMapping("/list")
	@ResponseBody
	R list(@RequestParam Map<String, Object> params)  throws Exception{
		
			Query query = new Query(params);
			List<Map<String,Object>> courses = courseService.list(query);
			for(Map<String,Object> c :courses) {
				if(c.get("courseOwner") != null) {
					Customer ct = customerService.get(Long.parseLong(c.get("courseOwner")+""));
					if(ct != null){
						c.put("ownerName",ct.getCustomerName());
					}
				}
			}
			PageInfo<Map<String,Object>> pageInfo = new PageInfo<Map<String,Object>>(courses);
			int total = (int)pageInfo.getTotal();
			PageUtils pageUtil = new PageUtils(courses, total);
			return new R("list",pageUtil);
	}

	
	@ApiOperation(value="微信课程查询", notes="根据条件查询课程", response=String.class)
	@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "课程id", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "bdId", value = "BD的id", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "courseTime", value = "开课日期", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "placeFirst", value = "一级地址", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "placeSecond", value = "二级地址", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "tradeArea", value = "课程商圈，精确匹配一级或二级地址中文名", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "ageRange", value = "宝宝年龄段id", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "ageRanges", value = "宝宝年龄段，起止以-分隔", required = false,paramType="query", dataType = "String"),
        @ApiImplicitParam(name = "coursePointRange", value = "课程点数,起止点数以-分隔", required = false,paramType="query", dataType = "String"),
        @ApiImplicitParam(name = "courseType", value = "课程类型", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "courseTypeName", value = "课程类型名称", required = false,paramType="query", dataType = "String"),
        @ApiImplicitParam(name = "courseSpec", value = "课程特性", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "courseStatus", value = "课程状态", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "lng", value = "经度值", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "lat", value = "纬度值", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true,paramType="query", dataType = "Integer"),
        @ApiImplicitParam(name = "pageNum", value = "当前页数", required = true,paramType="query", dataType = "Integer")
	})
	@GetMapping("/wxlist")
	@ResponseBody
	R wxlist(@RequestParam Map<String, Object> params)  throws Exception{
		if(params.get("ageRange") != null) {
			Long dictId1 = Long.parseLong(params.get("ageRange")+"");
			SysDictDO ageDict = sysDictService.get(dictId1);
			if(ageDict != null) {
				String val = ageDict.getValue();
				if(val != null && val.endsWith("月")) {
					val  = val.replaceFirst("月", "");
					String[] ageA = val.trim().split("-");
					if(ageA != null && ageA.length>1) {
						if(ageA[0].equals("")) {
							params.put("startAge", 0);
						}else {
							params.put("startAge", Integer.parseInt(ageA[0]));
						}
						if(ageA[1].equals("")) {
							params.put("endAge", 0);
						}else {
							params.put("endAge", Integer.parseInt(ageA[1]));
						}
					}
				}else if(val != null && val.endsWith("岁")) {
					val  = val.replaceFirst("岁", "");
					String[] ageA = val.trim().split("-");
					if(ageA != null && ageA.length>1) {
						if(ageA[0].equals("")) {
							params.put("startAge", 0);
						}else {
							params.put("startAge", Integer.parseInt(ageA[0])*12);
						}
						if(ageA[1].equals("")) {
							params.put("endAge", 0);
						}else {
							params.put("endAge", Integer.parseInt(ageA[1])*12);
						}
					}
				}
			}
		}
		
		if(params.get("ageRanges") != null) {
			String val = params.get("ageRanges")+"";
			if(val != null && val.endsWith("月")) {
				val  = val.replaceFirst("月", "");
				String[] ageA = val.trim().split("-");
				if(ageA != null && ageA.length>1) {
					if(ageA[0].equals("")) {
						params.put("startAge", 0);
					}else {
						params.put("startAge", Integer.parseInt(ageA[0]));
					}
					if(ageA[1].equals("")) {
						params.put("endAge", 0);
					}else {
						params.put("endAge", Integer.parseInt(ageA[1]));
					}
				}
			}else if(val != null && val.endsWith("岁")) {
				val  = val.replaceFirst("岁", "");
				String[] ageA = val.trim().split("-");
				if(ageA != null && ageA.length>1) {
					if(ageA[0].equals("")) {
						params.put("startAge", 0);
					}else {
						params.put("startAge", Integer.parseInt(ageA[0])*12);
					}
					if(ageA[1].equals("")) {
						params.put("endAge", 0);
					}else {
						params.put("endAge", Integer.parseInt(ageA[1])*12);
					}
				}
			}
		}
		
		if(params.get("coursePointRange") != null) {
				String[] pointA = (params.get("coursePointRange")+"").trim().split("-");
				if(pointA != null && pointA.length>1) {
					if(pointA[0].equals("")) {
						params.put("startPoint", null);
					}else {
						params.put("startPoint", Integer.parseInt(pointA[0]));
					}
					if(pointA[1].equals("")) {
						params.put("endPoint", null);
					}else {
						params.put("endPoint", Integer.parseInt(pointA[1]));
					}
				}
		}
		
		if(params.get("tradeArea") != null) {
			Map<String,Object> dictMap = new HashMap<String,Object>();
			dictMap.put("type", "address");
			dictMap.put("value", params.get("tradeArea"));
			List<SysDictDO> areaList = sysDictService.list(dictMap);
			if(areaList != null && areaList.size()>0) {
				String firstPlaceIds = "";
				String seconPlaceIds = "";
				for(SysDictDO dict: areaList) {
					if(dict.getParentId() == 0){
						firstPlaceIds += "," + dict.getId();
					}else {
						seconPlaceIds += "," + dict.getId();
					}
				}
				if(!"".equals(firstPlaceIds)) {
					params.put("placeFirst",firstPlaceIds.substring(1));
				}
				if(!"".equals(seconPlaceIds)) {
					params.put("placeSecond",seconPlaceIds.substring(1));
				}
			}
		}
		
		Query query = new Query(params);
		List<Map<String,Object>> courses = courseService.wxList(query);
		for(Map<String,Object> c :courses) {
			if(c.get("courseOwner") != null) {
				Customer ct = customerService.get(Long.parseLong(c.get("courseOwner")+""));
				if(ct != null){
					c.put("ownerName",ct.getCustomerName());
					if(params.get("lng") != null && params.get("lat") != null) {
						Double lng = ct.getLongitude();
						Double lat = ct.getLatitude();
						if(lng != null && lat != null) {
							try {
								c.put("distance", LocationUtil.getDistance(Double.parseDouble(params.get("lat")+""), Double.parseDouble(params.get("lng")+""), lat, lng));
							}catch(Exception e) {
								e.printStackTrace();
							}
						}else {
							c.put("distance", 0);
						}
					}else {
						c.put("distance", 0);
					}
				}
			}
		}
		PageInfo<Map<String,Object>> pageInfo = new PageInfo<Map<String,Object>>(courses);
		int total = (int)pageInfo.getTotal();
		PageUtils pageUtil = new PageUtils(courses, total);
		return new R("list",pageUtil);
	}

	

	@ApiOperation(value="微信推荐课程查询", notes="根据条件查询课程", response=String.class)
	@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "课程时间id", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "lng", value = "经度值", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "lat", value = "纬度值", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true,paramType="query", dataType = "Integer"),
        @ApiImplicitParam(name = "pageNum", value = "当前页数", required = true,paramType="query", dataType = "Integer")
	})
	@GetMapping("/recommendList")
	@ResponseBody
	R recommendList(@RequestParam Map<String, Object> params)  throws Exception{
		Query query = new Query(params);
		List<Map<String,Object>> courses = courseService.recommendList(query);
		for(Map<String,Object> c :courses) {
			if(c.get("courseOwner") != null) {
				Customer ct = customerService.get(Long.parseLong(c.get("courseOwner")+""));
				if(ct != null){
					c.put("ownerName",ct.getCustomerName());
					if(params.get("lng") != null && params.get("lat") != null) {
						Double lng = ct.getLongitude();
						Double lat = ct.getLatitude();
						if(lng != null && lat != null) {
							try {
								c.put("distance", LocationUtil.getDistance(Double.parseDouble(params.get("lat")+""), Double.parseDouble(params.get("lng")+""), lat, lng));
							}catch(Exception e) {
								e.printStackTrace();
							}
						}else {
							c.put("distance", 0);
						}
					}else {
						c.put("distance", 0);
					}
				}
			}
		}
		PageInfo<Map<String,Object>> pageInfo = new PageInfo<Map<String,Object>>(courses);
		int total = (int)pageInfo.getTotal();
		PageUtils pageUtil = new PageUtils(courses, total);
		return new R("list",pageUtil);
	}


	@ApiOperation(value="课程详情", notes="", response=String.class)
	@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "课程id", required = true,paramType="query",dataType = "Long"),
	})
	@GetMapping("/edit")
	@ResponseBody
	R edit(Long id)  throws Exception{
		return new R("obj",courseService.get(id));
	}

	
	@ApiOperation(value="课程和课程时间详情", notes="", response=String.class)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "subId", value = "课程时间id", required = true,paramType="query",dataType = "Long"),
        @ApiImplicitParam(name = "lng", value = "经度值", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "lat", value = "纬度值", required = false,paramType="query", dataType = "Long")
	})
	@GetMapping("/getDetail")
	@ResponseBody
	R getDetail(Long subId,Double lng, Double lat) throws Exception {
		CourseTime ct = courseTimeService.get(subId);
		if(ct == null) {
			return R.error("课程时间不存在");
		}
		Course c = courseService.get(ct.getCourseId());
		Customer cust = customerService.get(Long.parseLong(c.getCourseOwner()+""));
		if(lng != null && lat != null) {
			Double lng2 = cust.getLongitude();
			Double lat2 = cust.getLatitude();
			if(lng2 != null && lat2 != null) {
				c.setDistance( LocationUtil.getDistance(lat, lng, lat2, lng2));
			}else {
				c.setDistance("0");
			}
		}else {
			c.setDistance("0");
		}
	
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("course", c);
		result.put("courseTime", ct);
		result.put("customer", cust);
		return new R("obj",result);
	}
	
	@ApiOperation(value="课程保存", notes="", response=String.class)
	@PostMapping("/save")
	@ResponseBody
	R save(@RequestBody Course user)  throws Exception{
		if (courseService.save(user) > 0) {
			return R.saveOk(user.getId().toString());
		}
		return R.error();
	}

	@ApiOperation(value="课程更新", notes="", response=String.class)
	@PostMapping("/update")
	@ResponseBody
	R update(@RequestBody Course course)  throws Exception{
		
		if(course.getCurrentStep() == null) {
			course.setCourseStatus("0");
		}else if(course.getCurrentStep()>5) {
			course.setCourseStatus("1");
		}else {
			course.setCourseStatus("0");
		}
		if (courseService.update(course) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@ApiOperation(value="课程删除", notes="根据id删除", response=String.class)
	@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "课程id", required = true,paramType="query", dataType = "Long"),
	})
	@GetMapping("/remove")
	@ResponseBody
	R remove(Long id)  throws Exception{
		if (courseService.remove(id) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@PostMapping("/batchRemove")
	@ResponseBody
	R batchRemove(@RequestParam("ids[]") Long[] userIds)  throws Exception{
		List<Long> Ids = Arrays.asList(userIds);
		int r = courseService.batchremove(Ids);
		System.out.println(r);
		if (r > 0) {
			return R.ok();
		}
		return R.error();
	}

	@PostMapping("/exit")
	@ResponseBody
	boolean exit(@RequestParam Map<String, Object> params)  throws Exception{
		return !courseService.exit(params);// 存在，不通过，false
	}

	
	@ApiOperation(value="课程状态更新", notes="", response=String.class)
	@PostMapping("/updateStatus")
	@ResponseBody
	R updateStatus(@RequestBody Course user)  throws Exception{
		if (courseService.updateStatus(user) > 0) {
			return R.ok();
		}
		return R.error();
	}


}
